package com.ccit.springbootlaw.mapper;

import com.ccit.springbootlaw.pojo.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface UserMapper {
    // 根据ID查询用户
    @Select("SELECT name FROM users WHERE id = #{id}")
    User findById(int id);

    // 根据邮箱查询用户
    @Select("SELECT * FROM users WHERE email = #{email}")
    User findByEmail(String email);

    // 根据实体类内容进行多条件查找
    @Select("<script>" +
            "SELECT * FROM users " +
            "WHERE 1=1 " +
            "<if test='name != null and name != \"\"'>AND name LIKE CONCAT('%', #{name}, '%')</if> " +
            "<if test='email != null and email != \"\"'>AND email LIKE CONCAT('%', #{email}, '%')</if> " +
            "<if test='role != null and role != \"\"'>AND role = #{role}</if> " +
            "</script>")
    List<User> findUsersByConditions(User user);

    // 根据用户名或ID或邮箱查询用户，并验证密码
    @Select("SELECT * FROM users " +
            "WHERE (name = #{name} OR id = #{id} OR email = #{email}) " +
            "AND password = #{password}")
    User findUserByUsernameOrIdOrEmailAndVerifyPassword(User user);

    // 插入新用户
    @Insert("INSERT INTO users (name, email, password, role, created_at, updated_at) VALUES (#{name}, #{email}, #{password}, #{role}, NOW(), NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertUser(User user);

    // 更新用户信息
    @Update("<script>" +
            "UPDATE users " +
            "<set>" +
            "<if test='name != null and name != \"\"'>name = #{name},</if>" +
            "<if test='email != null and email != \"\"'>email = #{email},</if>" +
            "<if test='password != null and password != \"\"'>password = #{password},</if>" +
            "<if test='role != null and role != \"\"'>role = #{role},</if>" +
            "updated_at = NOW()" +
            "</set>" +
            "WHERE id = #{id}" +
            "</script>")
    int updateUser(User user);

    // 删除用户
    @Delete("DELETE FROM users WHERE id = #{id}")
    int deleteUserById(int id);

    // 查询所有用户
    @Select("SELECT * FROM users")
    List<User> findAllUsers();
}